#!/bin/bash

# ==========================================
# Calculator 模块 WASM 构建脚本
# ==========================================

MODULE_NAME="calculator"
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SOURCE_DIR/../../../.." && pwd)"
OUTPUT_DIR="$PROJECT_ROOT/dist/wasm"
OUTPUT_FILE="$OUTPUT_DIR/$MODULE_NAME.wasm"

echo "=========================================="
echo "构建 $MODULE_NAME 模块..."
echo "=========================================="

# 创建输出目录
mkdir -p "$OUTPUT_DIR"

# 检查源文件
SOURCE_FILE="$SOURCE_DIR/add.c"
if [ ! -f "$SOURCE_FILE" ]; then
  echo "❌ 源文件不存在: $SOURCE_FILE"
  exit 1
fi

# 编译 WASM
emcc "$SOURCE_FILE" \
  -o "$OUTPUT_FILE" \
  --no-entry \
  -s EXPORTED_FUNCTIONS='["_add","_multiply"]' \
  -s EXPORTED_RUNTIME_METHODS='["ccall","cwrap"]' \
  -s ALLOW_MEMORY_GROWTH=1 \
  -O3

# 检查编译结果
if [ -f "$OUTPUT_FILE" ]; then
  FILE_SIZE=$(ls -lh "$OUTPUT_FILE" | awk '{print $5}')
  echo "✅ $MODULE_NAME WASM 编译完成"
  echo "   源文件: $SOURCE_FILE"
  echo "   输出路径: $OUTPUT_FILE"
  echo "   文件大小: $FILE_SIZE"
else
  echo "❌ $MODULE_NAME WASM 编译失败"
  exit 1
fi

